#include "widget.h"
#include "ui_widget.h"

Widget::Widget(QWidget *parent)
    : QWidget(parent)
    , ui(new Ui::Widget)
{
    ui->setupUi(this);

    //连接数据库
    QSqlDatabase db = QSqlDatabase::addDatabase("QODBC");   //数据库驱动类型为SQL Server
    qDebug()<<"ODBC driver?"<<db.isValid();
    QString dsn = QString::fromLocal8Bit("mydsn");      //数据源名称
    db.setHostName("localhost");                        //选择本地主机，127.0.1.1
    db.setDatabaseName(dsn);                            //设置数据源名称
    db.setUserName("sa");                               //登录用户
    db.setPassword("802395");                           //密码

    if (db.open()){
        QMessageBox::information(this, "连接提示", "连接成功");
    }//if
    else{
        QMessageBox::warning(this, "连接提示", "连接失败");
    }
}

Widget::~Widget()
{
    delete ui;
}


void Widget::on_insertPushButton_clicked()
{
    QString id = ui->idLineEdit->text();
    QString name = ui->nameLineEdit->text();
    QString birth = ui->birthLineEdit->text();

    //类似C的输入
    QString sql = QString("insert into student values(%1, '%2', '%3');").arg(id).arg(name).arg(birth);
    //进行插入
    QSqlQuery query;
    if (query.exec(sql)){
        QMessageBox::information(this, "插入提示", "插入成功");
    }
    else{
        QMessageBox::information(this, "插入提示", "插入失败");
    }
}


void Widget::on_findPushButton_clicked()
{
    QSqlQuery query;
    query.exec("select * from student");
    //查询结束的边界
    while (query.next()){
        qDebug() << query.value(0);
        qDebug() << query.value(1);
        qDebug() << query.value(2);
    }
}

